/* eslint-disable no-undef */
import axios from 'axios'
import type {AxiosRequestConfig} from "axios"
import {useUserInfo} from "../store/moduls/userinfo";

const BaseUrl = import.meta.env.VITE_RES_URL || "/proxy/"
import {Ref} from "vue"

interface loadingtype {
    [prop: string]: Ref<boolean>
}

const loadingstorage: loadingtype = {} // 所有加载状态的仓库，key是url，value是ref数据，保证这边修改，那边同步修改
const createService = () => {
    return axios.create({
        // 联调
        // baseURL: process.env.NODE_ENV === 'mock' ? `/api/` : '/proxy/',
        baseURL: BaseUrl,
        // 是否跨站点访问控制请求
        withCredentials: false,
        timeout: 10000,
        // 请求数据拦截
        // transformRequest: [
        //     (data) => {
        //         return data
        //     },
        // ],
        validateStatus() {
            // 使用async-await，处理reject情况较为繁琐，所以全部返回resolve，在业务代码中处理异常
            return true
        },
        // 响应数据拦截
        transformResponse: [
            (data) => {
                if (typeof data === 'string' && data.startsWith('{') || data.startsWith('[')) {
                    data = JSON.parse(data)
                }
                return data
            },
        ],
    })
}
const service = createService()
// 请求拦截器
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        console.log("请求拦截1")
        // 手动添加jwt-token
        // if (store.getters["userinfo/jwttoken"]) {
        //     config.headers['Authorization'] = store.getters["userinfo/jwttoken"]
        // }
        // 手动添加密钥ID
        // if(store.state.encryption.encryptionID){
        //     config.headers["encryptionID"] = store.state.encryption.encryptionID
        // }
        const userInfo = useUserInfo()
        if (userInfo.token) {
            // @ts-ignore
            config.headers['Authorization'] = "jwt " + userInfo.token
        }
        return config
    },
    (error) => {
        console.log("请求拦截2")
        // 错误抛到业务代码
        return Promise.resolve(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        console.log("响应拦截1")
        // 状态码在200多是正常回复，超过300的由拦截器处理
        if (response.status === 404) {
            return Promise.reject(response)
        } else if (response.status >= 500) {
            return Promise.reject(response)
        } else if (response.status === 401) {
            return Promise.reject(response)
        } else if (response.status >= 300) {
            return Promise.reject(response)
        } else {
            return response
        }
    },
    (error): string => {
        // 错误的时候，如果这个url对应的ref属性还在，设置为false，然后删除掉。
        if (loadingstorage[error.confi.url] && loadingstorage[error.confi.url].value) {
            loadingstorage[error.confi.url].value = false;
            delete loadingstorage[error.confi.url]
        }
        return error.message
    }
)

export function json(url: string, data = null, loading: null | Ref<boolean>) {
    let loadingkey:string
    if (loading != null) {
        loading.value = true;
        loadingkey = url + new Date().getTime()
        loadingstorage[loadingkey] = loading
    }
    return service({
        method: "post",
        url: url,
        data: data,
        headers: {'Content-Type': 'application/json;charset=utf-8',},
        loadingkey: loadingkey,
    })
}

export function update(url: string, data = null, id = null) {
    if (id) {
        return service({
            method: "put",
            url: url + id + "/",
            data: data,
            headers: {'Content-Type': 'application/json;charset=utf-8',}
        })
    } else {
        return service({
            method: "put",
            url: url,
            data: data,
            headers: {'Content-Type': 'application/json;charset=utf-8',}
        })
    }
}

export function shanchu(url: string, data = null, id = null) {
    if (id) {
        return service({
            method: "delete",
            url: url + id + "/",
            params: data,
            headers: {'Content-Type': 'application/json;charset=utf-8',}
        })
    } else {
        return service({
            method: "delete",
            url: url,
            params: data,
            headers: {'Content-Type': 'application/json;charset=utf-8',}
        })
    }
}

export function get(url: string, data = null, id = null) {
    if (id) {
        return service({
            method: "get",
            url: url + id + "/",
            params: data,
        })
    } else {
        return service({
            method: "get",
            url: url,
            params: data,
        })
    }

}

export function list(url: string, data = null) {
    return service({
        method: "get",
        url: url,
        params: data,
    })
}

export function form(url: string, data = null) {
    return service({
        method: "post",
        url: url,
        data: data,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        // transformRequest: [function (data) {
        //     let ret = ''
        //     for (const it in data) {
        //         ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        //     }
        //     return ret
        // }]
    })
}

export default service
